package net.slenderloris.TouchServer;

import java.awt.Point;

public class KeyboardTrainer {

	public static class Key {
		private static final int NUM_AVERAGE_POINTS = 10;
		char mLetter;
		Point mPos[] = new Point[NUM_AVERAGE_POINTS];
		int mPosIndex = 0;
		int mPosCount = 0;
		
		public Key(char letter) {
			mLetter = letter;
		}
		
		public Point getAveragePosition() {
			Point average = null;
			if(mPosCount>0) {
				average = new Point(mPos[0]);
				for(int i=1; i<mPosCount; i++) {
					average.x += mPos[i].x;
					average.y += mPos[i].y;
				}
				average.x /= mPosCount;
				average.y /= mPosCount;
			}
			return average;
		}
		
		public void addPos(Point p) {
			if(mPos[mPosIndex]==null) {
				mPos[mPosIndex] = new Point(p);
			} else {
				mPos[mPosIndex].setLocation(p.x, p.y);
			}
			mPosIndex=(mPosIndex+1)%NUM_AVERAGE_POINTS;
			if(mPosCount<NUM_AVERAGE_POINTS) {
				mPosCount++;
			}
		}
	}

	private static final char chars[] = { 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z' };

	private Key mKeys[];
	private int mCurrentKeyIndex;
	
	public KeyboardTrainer() {
		mCurrentKeyIndex = 0;
		mKeys = new Key[chars.length];
		int i=0;
		for(char c : chars) {
			mKeys[i++] = new Key(c);
		}
	}
	
	public char getCurrentLetter() {
		return mKeys[mCurrentKeyIndex].mLetter;
	}
	
	public void tapped(Point p) {
		mKeys[mCurrentKeyIndex].addPos(p);
		mCurrentKeyIndex=(mCurrentKeyIndex+1)%(mKeys.length);
	}
	
	public char getNearestLetter(Point p) {
		char ret = 'A';
		int nearest = Integer.MAX_VALUE;
		for(Key k : mKeys) {
			Point av = k.getAveragePosition();
			if(av!=null) {
				int dx = av.x-p.x;
				int dy = av.y-p.y;
				int dsq = (dx*dx)+(dy*dy);
				if(dsq<nearest) {
					ret = k.mLetter;
					nearest = dsq;
				}
			}
		}
		return ret;
	}
	
	public Key getKey(int index) {
		return mKeys[index];
	}
	
}
